package com.zenith.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zenith.user.mapper.UserMapper;
import com.zenith.user.po.domain.User;
import com.zenith.user.po.domain.UserRole;
import com.zenith.user.po.dto.UserDTO;
import com.zenith.user.po.vo.UserVO;
import com.zenith.user.service.UserRoleService;
import com.zenith.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zenith.common.result.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.zenith.common.enumcode.RedisEnum.USER_INFO_KEY;
import static com.zenith.common.enumcode.RedisEnum.USER_LIST_KEY;

/**
 * 用户 业务实现
 *
 * @author makejava
 * @since 2025-08-15
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    private static final long CACHE_TIMEOUT = 3600;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public PageResult<User> getUserPage(UserDTO query) {
        // 创建分页对象
        Page<User> page = new Page<>(query.getPageNum() != null ? query.getPageNum() : 1, 
                                   query.getPageSize() != null ? query.getPageSize() : 10);

        // 执行分页查询
        Page<User> pageResult = lambdaQuery().page(page);
        
        // 封装返回结果
        PageResult<User> result = PageResult.ofPage(page.getCurrent(), page.getSize(), pageResult.getTotal(), pageResult.getRecords());
        log.info("缓存用户分页数据: pageNum={}, pageSize={}", query.getPageNum(), query.getPageSize());
        
        return result;
    }

    @Override
    public User getUserByUsername(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }

        // 从数据库查询
        User user = lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getIsDelete, 0)
                .one();

        return user;
    }
    
    @Override
    public User getUserById(Long id) {
        if (id == null) {
            return null;
        }
        // 从数据库查询
        User user = lambdaQuery()
                .eq(User::getId, id)
                .eq(User::getIsDelete, 0)
                .one();

        return user;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createUser(UserDTO userDTO) {
        if (userDTO == null || !StringUtils.hasText(userDTO.getUsername())) {
            throw new IllegalArgumentException("用户信息不能为空");
        }
        
        // 检查用户名是否已存在
        if (getUserByUsername(userDTO.getUsername()) != null) {
            throw new IllegalArgumentException("用户名已存在: " + userDTO.getUsername());
        }
        
        // 转换DTO到实体
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        
        // 加密密码
        if (StringUtils.hasText(userDTO.getPassword())) {
            user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        }
        
        // 设置默认值
        user.setStatus(1);
        user.setIsDelete(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        // 保存用户
        boolean result = save(user);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(UserDTO userDTO) {
        if (userDTO == null || userDTO.getId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        
        // 获取原用户信息
        User existingUser = getUserById(userDTO.getId());
        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在: ID=" + userDTO.getId());
        }
        
        // 如果更新用户名，需要检查是否重复
        if (StringUtils.hasText(userDTO.getUsername()) && 
            !userDTO.getUsername().equals(existingUser.getUsername())) {
            if (getUserByUsername(userDTO.getUsername()) != null) {
                throw new IllegalArgumentException("用户名已存在: " + userDTO.getUsername());
            }
        }
        
        // 构建更新条件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, userDTO.getId())
                    .eq(User::getIsDelete, 0);
        
        // 设置更新字段
        if (StringUtils.hasText(userDTO.getUsername())) {
            updateWrapper.set(User::getUsername, userDTO.getUsername());
        }
        if (StringUtils.hasText(userDTO.getRealName())) {
            updateWrapper.set(User::getRealName, userDTO.getRealName());
        }
        if (StringUtils.hasText(userDTO.getPhone())) {
            updateWrapper.set(User::getPhone, userDTO.getPhone());
        }
        if (StringUtils.hasText(userDTO.getEmail())) {
            updateWrapper.set(User::getEmail, userDTO.getEmail());
        }
        if (StringUtils.hasText(userDTO.getAvatar())) {
            updateWrapper.set(User::getAvatar, userDTO.getAvatar());
        }
        if (userDTO.getStatus() != null) {
            updateWrapper.set(User::getStatus, userDTO.getStatus());
        }
        if (StringUtils.hasText(userDTO.getPassword())) {
            updateWrapper.set(User::getPassword, passwordEncoder.encode(userDTO.getPassword()));
        }
        updateWrapper.set(User::getUpdateTime, LocalDateTime.now());
        
        // 执行更新
        boolean result = update(updateWrapper);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        
        // 获取用户信息
        User user = getUserById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在: ID=" + id);
        }
        
        // 构建删除条件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, id)
                    .eq(User::getIsDelete, 0)
                    .set(User::getIsDelete, 1)
                    .set(User::getUpdateTime, LocalDateTime.now());
        
        // 执行逻辑删除
        boolean result = update(updateWrapper);
        
        return result;
    }
    
    @Override
    public List<UserVO> getUsersByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return List.of();
        }
        
        // 从数据库查询
        List<User> users = lambdaQuery()
                .in(User::getId, ids)
                .eq(User::getIsDelete, 0)
                .list();
        
        // 转换为VO
        return users.stream()
                .map(user -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(user, userVO);
                    return userVO;
                })
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserStatus(Long id, Integer status) {
        if (id == null || status == null) {
            throw new IllegalArgumentException("用户ID和状态不能为空");
        }
        
        // 构建更新条件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, id)
                    .eq(User::getIsDelete, 0)
                    .set(User::getStatus, status)
                    .set(User::getUpdateTime, LocalDateTime.now());
        
        boolean result = update(updateWrapper);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetPassword(Long id, String newPassword) {
        if (id == null || !StringUtils.hasText(newPassword)) {
            throw new IllegalArgumentException("用户ID和新密码不能为空");
        }
        
        // 构建更新条件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, id)
                    .eq(User::getIsDelete, 0)
                    .set(User::getPassword, passwordEncoder.encode(newPassword))
                    .set(User::getUpdateTime, LocalDateTime.now());
        
        boolean result = update(updateWrapper);
    
        return result;
    }

    @Override
    public UserVO getCurrentUserInfo(Long userId) {
        User user = getUserById(userId);
        if (user == null) {
            return null;
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public boolean updateUserProfile(UserDTO userDTO) {
        return updateUser(userDTO);
    }

    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        if (userId == null || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 获取用户信息
        User user = getUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new IllegalArgumentException("旧密码错误");
        }
        
        // 更新密码
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, userId)
                    .eq(User::getIsDelete, 0)
                    .set(User::getPassword, passwordEncoder.encode(newPassword))
                    .set(User::getUpdateTime, LocalDateTime.now());
        
        boolean result = update(updateWrapper);
    
        return result;
    }

    @Override
    public boolean updateAvatar(Long userId, String avatarUrl) {
        if (userId == null || !StringUtils.hasText(avatarUrl)) {
            throw new IllegalArgumentException("用户ID和头像URL不能为空");
        }
        
        // 构建更新条件
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, userId)
                    .eq(User::getIsDelete, 0)
                    .set(User::getAvatar, avatarUrl)
                    .set(User::getUpdateTime, LocalDateTime.now());
        
        boolean result = update(updateWrapper);
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAssignRoles(List<Long> userIds, List<Long> roleIds) {
        if (userIds == null || userIds.isEmpty() || roleIds == null || roleIds.isEmpty()) {
            throw new IllegalArgumentException("用户ID列表和角色ID列表不能为空");
        }
        log.info("批量分配用户角色: userIds={}, roleIds={}", userIds, roleIds);
        // 实现批量分配角色逻辑
        boolean result = false;
        for (Long userId : userIds) {
            for (Long roleId : roleIds) {
                QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", userId)
                        .eq("role_id", roleId);
                userRoleService.remove(queryWrapper);
                userRoleService.save(new UserRole(userId, roleId));
            }
        }
        log.warn("批量分配用户角色功能尚未实现");
        return false;
    }

    @Override
    public PageResult<UserVO> searchUsers(String keyword, Integer status, String role, Integer pageNum, Integer pageSize) {
        // 创建分页对象
        Page<User> page = new Page<>(pageNum != null ? pageNum : 1, 
                                   pageSize != null ? pageSize : 10);
        
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getIsDelete, 0);
        
        // 添加搜索条件
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> 
                wrapper.like(User::getUsername, keyword)
                      .or()
                      .like(User::getRealName, keyword)
                      .or()
                      .like(User::getPhone, keyword)
            );
        }
        
        if (status != null) {
            queryWrapper.eq(User::getStatus, status);
        }
        
        if (StringUtils.hasText(role)) {
            queryWrapper.eq(User::getRole, role);
        }
        
        // 执行分页查询
        Page<User> pageResult = page(page, queryWrapper);
        
        // 转换为VO
        List<UserVO> userVOs = pageResult.getRecords().stream()
                .map(user -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(user, userVO);
                    return userVO;
                })
                .collect(Collectors.toList());
        
        // 封装返回结果
        return PageResult.ofPage(page.getCurrent(), page.getSize(), pageResult.getTotal(), userVOs);
    }
}